import requests
import datetime
import time
import json
from application import db
from lxml import etree
from sqlalchemy import text


class JobTask():
    def json_num(self, id_lt, result_lt):

        for i in id_lt:
            if "失效" in i.get("title"):
                print("失效")
            else:
                BV = i.get("bv_id", "no")
                title = i.get("title", "no")
                jianjie = i.get("intro", "no")
                love_num = i.get("cnt_info").get("collect", 1)
                bofang = i.get("cnt_info").get("play", 1)
                img_url = i.get("cover", "no")
                up_img_url = i.get("upper").get("face", "no")
                create_time = i.get("ctime", "no")
                timeArray = time.localtime(int(create_time))
                create_time_new = time.strftime('%Y-%m-%d', timeArray)
                new_time = datetime.datetime.now().strftime('%Y-%m-%d')
                if BV in result_lt:
                    print("已存在~~~")
                else:
                    sql = "INSERT INTO lsp(title,BV,bofang_num,create_time,newtime,jianjie,love_num,img_url,up_img_url)VALUES ('%s','%s','%s','%s','%s','%s','%s','%s','%s')" % (
                        title, BV, int(bofang), create_time_new, new_time, jianjie, int(love_num), img_url, up_img_url)
                    try:
                        db.engine.execute(sql)
                    except:
                        print("错误")

    def run(self, params):
        sql = text("select BV from `lsp`")
        result = db.engine.execute(sql)
        result_lt = list()
        for i in result:
            result_lt.append(i[0])
        headers = {
            "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/98.0.4758.102 Safari/537.36"
        }
        for i in range(1, 7):
            url = "https://api.bilibili.com/x/v3/fav/resource/list?media_id=1518489371&pn={}&ps=20&keyword=&order=view&type=0&tid=0&platform=web&jsonp=jsonp".format(
                str(i))
            response2 = requests.get(
                url=url,
                headers=headers)
            content2 = json.loads(response2.text)
            id_lt = content2.get("data").get("medias")
            self.json_num(id_lt, result_lt)

        pass
